package es.htic.arq.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class POIXLSUtils {

	public static HSSFWorkbook getHSSFWorkbook (File file) {
		InputStream stream	= null;
		HSSFWorkbook wb		= null;

		try {
			stream	= new FileInputStream(file);
			wb		= new HSSFWorkbook(stream);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (stream!=null) {
				try {
					stream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return wb;
	}

	public static String getStringValue(HSSFSheet sheet, int rowIndex, int cellIndex) {
		String result = null;

		Object value = getValue(sheet, rowIndex, cellIndex);
		if (value != null) {
			result = value.toString();
		}
		return result;
	}

	public static Object getValue(HSSFSheet sheet, int rowIndex, int cellIndex) {
		HSSFRow row		= sheet.getRow(rowIndex);
		HSSFCell cell	= row.getCell(cellIndex);

		switch (cell.getCellType()) {
			case HSSFCell.CELL_TYPE_STRING:
				return cell.getRichStringCellValue().getString();
			case HSSFCell.CELL_TYPE_NUMERIC:
				if (HSSFDateUtil.isCellDateFormatted(cell)) {
					return cell.getDateCellValue();
				} else {
					return cell.getNumericCellValue();
				}
			case HSSFCell.CELL_TYPE_BOOLEAN:
				return cell.getBooleanCellValue();
			case HSSFCell.CELL_TYPE_FORMULA:
				return cell.getCellFormula();
			default:
				return null;
		}
	}

}